package com.xjnt.mnui.service;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.xjnt.frameworks.annotation.Service;
import com.xjnt.frameworks.core.BaseService;
import com.xjnt.frameworks.plugin.sql.consts.FetchMode;
import com.xjnt.frameworks.plugin.sql.criterion.Restrictions;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;
import com.xjnt.frameworks.web.constants.SearchType;
import com.xjnt.mnui.entity.Card;
import com.xjnt.mnui.entity.CardUser;
import com.xjnt.mnui.entity.Portal;

@Service
public class CardService extends BaseService<Card> {

	@Override
	public Card getModel() {
		return Card.me;
	}

	@Override
	protected SqlCriteria getCriteria(Map<String, String[]> conditions,
			SearchType searchType) {
		SqlCriteria criteria = new SqlCriteria(getModel(), "card");
		criteria.addRelation(CardUser.me, "user", FetchMode.FETCH);
		criteria.addRelation(Portal.me, "portal", FetchMode.FETCH);
		criteria.add(Restrictions.eqProp("card.userid", "user.uuid"));
		criteria.add(Restrictions.eqProp("card.portalid", "portal.uuid"));
		if (conditions != null) {
			Map<String, Class<?>> columnMap = getModel().getTable()
					.getColumnTypeMap();
			Set<Entry<String, String[]>> setCondition = conditions.entrySet();
			Iterator<Entry<String, String[]>> itCondition = setCondition
					.iterator();
			while (itCondition.hasNext()) {
				Entry<String, String[]> entry = itCondition.next();
				String conditionName = entry.getKey();
				String[] conditionVal = entry.getValue();
				String[] tmpNames = conditionName.split("\\.");
				String colName = conditionName;
				if (tmpNames.length > 1) {
					colName = tmpNames[1];
				}
				boolean hasColumn = getModel().getTable().hasColumnLabel(
						colName);
				if (hasColumn) {
					Class<?> colType = columnMap.get(colName);
					combine(criteria, conditionName, conditionVal, colType,
							searchType);
				}
			}
			Object[] sortName = conditions.get("sortName");
			Object[] sortOrder = conditions.get("sortOrder");
			orderCondition(criteria, sortName, sortOrder);
		}
		return criteria;
	}
	
	public Card findCardByIccid(String iccid){
		SqlCriteria criteria = new SqlCriteria(getModel(), "card");
		criteria.addRelation(Portal.me, "portal", FetchMode.FETCH);
		criteria.add(Restrictions.eqProp("card.portalid", "portal.uuid"));
		criteria.add(Restrictions.eq("card.iccid", iccid));
		String sql = criteria.toSql();
		return getModel().findFirst(sql, iccid);
	}
}
